<template>
  <view class="contract-management">
    <header-vue :back="true" :title="title"></header-vue>
    <view class="contract-management-content">
      <!-- 搜索框 -->
      <view class="search-box">
        <u-icon name="search" color="#999" size="20"></u-icon>
        <input
          v-model="searchText"
          placeholder="搜索文件名称"
          class="search-input"
          @confirm="handleSearch"
        />
      </view>

      <!-- 合同列表 -->
      <scroll-view class="contract-list" scroll-y>
        <u-checkbox-group v-model="selectedIds" @change="handleGroupChange">
          <view
            v-for="(contract, index) in filteredContracts"
            :key="contract.id"
            class="contract-item"
            @click="onDetailClick(contract, index)"
          >
            <view class="contract-checkbox">
              <u-checkbox
                :name="contract.id"
                activeColor="#1890ff"
              ></u-checkbox>
            </view>

            <view class="contract-icon">
              <image
                :src="IMAGE_URL+'/static/master/pdf-ico.png'"
                style="width: 36rpx; height: 40rpx"
              />
            </view>

            <view class="contract-info">
              <text class="contract-name">{{ contract.name }}</text>
              <view class="contract-meta">
                <text class="file-size">{{ contract.size }}</text>
                <text class="upload-time">{{ contract.time }}</text>
              </view>
            </view>

            <view class="contract-actions">
              <u-icon
                name="download"
                color="#1890ff"
                size="20"
                @click="handleDownload(contract)"
              ></u-icon>
            </view>
          </view>
        </u-checkbox-group>

        <!-- 空状态 -->
        <view v-if="filteredContracts.length === 0" class="empty-state">
          <u-icon name="file-text" color="#ccc" size="60"></u-icon>
          <text class="empty-text">暂无合同文件</text>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="bottom-actions">
        <view class="select-all">
          <u-checkbox
            v-model="selectAll"
            @change="handleSelectAll"
            :label="'全部'"
            activeColor="#1890ff"
          ></u-checkbox>
        </view>

        <view class="action-buttons">
          <button class="btn btn-upload" @click="handleUpload">上传</button>
          <button class="btn btn-download" @click="handleDownloadSelected">
            下载
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import headerVue from "@/components/header.vue";
import appConfig from '@/config/app.js'

export default {
  data() {
    return {
       IMAGE_URL: appConfig.IMAGE_URL,
      title: "合同管理",
      searchText: "",
      selectAll: false,
      selectedIds: [], // 存储选中的合同ID
      contracts: [
        {
          id: 1,
          name: "人月嫂包吃住一个月合同.pdf",
          size: "1.2M",
          time: "2025-06-11 14:22",
        },
        {
          id: 2,
          name: "人月嫂包吃住一个月合同.pdf",
          size: "1.2M",
          time: "2025-06-11 14:22",
        },
        {
          id: 3,
          name: "人月嫂包吃住一个月合同.pdf",
          size: "1.2M",
          time: "2025-06-11 14:22",
        },
        {
          id: 4,
          name: "人月嫂包吃住一个月合同.pdf",
          size: "1.2M",
          time: "2025-06-11 14:22",
        },
      ],
    };
  },
  components: {
    headerVue,
  },
  computed: {
    filteredContracts() {
      if (!this.searchText) {
        return this.contracts;
      }
      return this.contracts.filter((contract) =>
        contract.name.toLowerCase().includes(this.searchText.toLowerCase())
      );
    },
    selectedCount() {
      return this.selectedIds.length;
    },
  },
  watch: {
    selectedCount(newVal) {
      // 当选中数量等于列表数量时，自动勾选全选
      this.selectAll =
        newVal === this.contracts.length && this.contracts.length > 0;
    },
    contracts: {
      handler() {
        // 当合同列表变化时，更新全选状态
        this.selectAll =
          this.selectedIds.length === this.contracts.length &&
          this.contracts.length > 0;
      },
      deep: true,
    },
  },
  methods: {
    // 搜索处理
    handleSearch() {
      console.log("搜索:", this.searchText);
    },

    // 全选/取消全选
    handleSelectAll(checked) {
      if (checked) {
        // 全选：将所有合同的ID添加到selectedIds
        this.selectedIds = this.contracts.map((contract) => contract.id);
      } else {
        // 取消全选：清空selectedIds
        this.selectedIds = [];
      }
    },

    // 复选框组变化
    handleGroupChange(ids) {
      this.selectedIds = ids;
    },
    onDetailClick(contract, index) {
      console.log("点击合同详情:", contract.name, index);
      uni.navigateTo({
        url: `/views-master/my/contract-management-detail?contractId=${contract.id}&index=${index}`,
      });
    },
    // 上传文件
    handleUpload() {
      uni.chooseMessageFile({
        count: 1,
        type: "file",
        extension: ["pdf", "doc", "docx"],
        success: (res) => {
          const tempFile = res.tempFiles[0];
          const newContract = {
            id: Date.now(),
            name: tempFile.name,
            size: this.formatFileSize(tempFile.size),
            time: this.getCurrentTime(),
          };
          this.contracts.unshift(newContract);
          uni.showToast({
            title: "上传成功",
            icon: "success",
          });
        },
      });
    },

    // 下载单个文件
    handleDownload(contract) {
      uni.showLoading({ title: "下载中..." });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: "开始下载",
          icon: "success",
        });
        console.log("下载文件:", contract.name);
      }, 1000);
    },

    // 下载选中的文件
    handleDownloadSelected() {
      if (this.selectedIds.length === 0) {
        uni.showToast({
          title: "请先选择文件",
          icon: "none",
        });
        return;
      }

      const selectedCount = this.selectedIds.length;
      uni.showLoading({ title: `准备下载${selectedCount}个文件` });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: `开始下载${selectedCount}个文件`,
          icon: "success",
        });
      }, 1500);
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return "0 B";
      const k = 1024;
      const sizes = ["B", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toFixed(1) + sizes[i];
    },

    // 获取当前时间
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
  },
};
</script>

<style lang="scss" scoped>
.contract-management {
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 100%;
  overflow: hidden;
  position: relative;
  background: linear-gradient(180deg, #f3f6fc 0%, #ffffff 100%);

  .contract-management-content {
    flex: 1;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 28rpx 32rpx;
  }

  .search-box {
    display: flex;
    align-items: center;
    width: 100%;
    height: 72rpx;
    background: #ffffff;
    box-shadow: 0rpx 0rpx 12rpx 0rpx rgba(0, 0, 0, 0.08);
    border-radius: 60rpx 60rpx 60rpx 60rpx;
    padding: 0 28rpx;
    box-sizing: border-box;
    margin-bottom: 28rpx;
  }

  .search-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    margin-left: 10rpx;
    background: transparent;

    &::placeholder {
      color: #999;
    }
  }

  .contract-list {
    flex: 1;
    box-sizing: border-box;
  }
  ::v-deep .u-checkbox-group {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    width: 100%;
  }

  .contract-item {
    display: flex;
    align-items: center;
    background: #fff;
    padding: 28rpx;
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(0, 0, 0, 0.1);
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    margin-bottom: 28rpx;
  }

  .contract-checkbox {
    margin-right: 20rpx;
  }

  .contract-icon {
    margin-right: 20rpx;
  }

  .contract-info {
    flex: 1;
  }

  .contract-name {
    display: block;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 8rpx;
  }

  .contract-meta {
    display: flex;
    align-items: center;
  }

  .file-size {
    font-size: 24rpx;
    color: #999;
  }

  .upload-time {
    font-size: 24rpx;
    color: #999;
    margin-left: 20rpx;
  }

  .contract-actions {
    padding: 10rpx;
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    color: #ccc;
  }

  .empty-text {
    font-size: 28rpx;
    margin-top: 20rpx;
    color: #999;
  }

  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 750rpx;
    // height: 156rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
    padding: 6px 32rpx;
    box-sizing: border-box;

    background: #ffffff;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(0, 0, 0, 0.06);
  }

  .select-all {
    flex: 1;
  }

  .action-buttons {
    display: flex;
    gap: 20rpx;
  }

  .btn-upload {
    color: #fff;
    font-size: 36rpx;
    border: none;
    margin: 0;
    width: 228rpx;
    line-height: 76rpx;
    height: 76rpx;
    background: linear-gradient(90deg, #df9824 0%, #f4b042 100%);
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(223, 152, 36, 0.1);
    border-radius: 60rpx 60rpx 60rpx 60rpx;
    &:active {
      border: none;
      background: linear-gradient(90deg, #df9824 0%, #f4b042 100%);
    }
  }

  .btn-download {
    color: #fff;
    font-size: 36rpx;
    border: none;
    margin: 0;
    width: 228rpx;
    line-height: 76rpx;
    height: 76rpx;
    background: linear-gradient(90deg, #0785cf 0%, #25a4ef 100%);
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(223, 152, 36, 0.1);
    border-radius: 60rpx 60rpx 60rpx 60rpx;
    &:active {
      border: none;
      background: linear-gradient(90deg, #0785cf 0%, #25a4ef 100%);
    }
  }
}
</style>
